package com.cq.hd.product.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cq.hd.product.api.dto.ActiveLabelDto;
import com.cq.hd.product.api.vo.LabelReferenceStatVo;
import com.cq.hd.product.mapper.TbActiveLabelMapper;
import com.cq.hd.product.po.TbActiveLabelPo;
import com.cq.hd.product.service.TbActiveLabelService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author much
 * @since 2024/05/18 20:40
 */
@Service
public class TbActiveLabelServiceImpl extends ServiceImpl<TbActiveLabelMapper, TbActiveLabelPo>
        implements TbActiveLabelService {

    @Transactional
    @Override
    public void saveActiveLabels(Long activeId, List<Long> labelIds) {
        baseMapper.deleteByActiveId(activeId);

        if (CollectionUtils.isNotEmpty(labelIds)) {
            List<TbActiveLabelPo> collect = labelIds.stream()
                    .map(labelId -> convertToPo(activeId, labelId)).collect(Collectors.toList());
            saveBatch(collect);
        }
    }

    @Override
    public List<ActiveLabelDto> getActiveLabels(Long activeId) {
        return baseMapper.selectActiveLabels(activeId);
    }

    /**
     * 统计标签被引用的次数
     *
     * @param labelIds 标签ids
     * @return <label_id, reference_count>
     */
    @Override
    public Map<Long, Integer> getLabelReferenceCounts(List<Long> labelIds) {
        if (CollectionUtils.isEmpty(labelIds)) {
            return Collections.emptyMap();
        }

        List<LabelReferenceStatVo> labelReferenceStatVos = baseMapper.countLabelReferences(labelIds);
        if (CollectionUtils.isEmpty(labelReferenceStatVos)) {
            return Collections.emptyMap();
        }
        return labelReferenceStatVos.stream()
                .collect(Collectors.toMap(LabelReferenceStatVo::getLabelId, LabelReferenceStatVo::getReferenceCount));
    }

    private TbActiveLabelPo convertToPo(Long activeId, Long labelId) {
        TbActiveLabelPo activeLabelPo = new TbActiveLabelPo();
        activeLabelPo.setActiveId(activeId);
        activeLabelPo.setLabelId(labelId);
        activeLabelPo.setCreateTime(LocalDateTime.now());
        return activeLabelPo;
    }

}
